package com.dys.proxy3;


import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author: 疾风
 * @ClassName: MyCglibInterceptor
 * @Description: TODO
 * @CreateDate: 2024/10/21
 * @Version: v1.0.0
 */
public class MyCglibInterceptor implements MethodInterceptor {
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("---------before cglib interceptor---------");
        Object result = methodProxy.invokeSuper(o, objects);
        System.out.println("---------after cglib interceptor---------");
        return result;
    }

    /**
     * 获取目标对象的代理对象
     * @return 代理对象
     */
    public static Object createCglibProxy(Class cls,MethodInterceptor interceptor) {
        Enhancer enhancer = new Enhancer();
        // 生成指定类的子类，也就是重写类中的业务方法
        enhancer.setSuperclass(cls);
        // 设置回调函数，加入intercept()方法
        enhancer.setCallback(interceptor);
        return enhancer.create();
    }
}
